﻿using Nacos.V2;
using Newtonsoft.Json;
using Ocelot.Cache;
using Ocelot.Configuration.File;
using Ocelot.Configuration.Repository;
using Ocelot.Responses;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ocelot.Provider.Nacos;

public class NacosFileConfigurationRepository : IFileConfigurationRepository
{
    private readonly INacosConfigService _nacosConfigService;
    private readonly IOcelotCache<FileConfiguration> _cache;
    public NacosFileConfigurationRepository(INacosConfigService nacosConfigService,IOcelotCache<FileConfiguration> cache)
    {
        _nacosConfigService = nacosConfigService;
        _cache = cache;
    }

    public async Task<Response<FileConfiguration>> Get()
    {
        var config = _cache.Get("Nacos" + "FileConfiguration", "");

        if (config != null)
        {
            return new OkResponse<FileConfiguration>(config);
        }

        //提取信息
        var nacosConfig = await _nacosConfigService.GetConfig("gateway", "DEFAULT_GROUP", 5000L);

        var file =JsonConvert.DeserializeObject<FileConfiguration>(nacosConfig);

        if (file.Routes == null || file.Routes.Count == 0)
        {
            return new OkResponse<FileConfiguration>(null);
        }
        return new OkResponse<FileConfiguration>(file);
    }

    public Task<Response> Set(FileConfiguration fileConfiguration)
    {
        _cache.AddAndDelete("Nacos" + "FileConfiguration", fileConfiguration, TimeSpan.FromSeconds(1800), "");
        return Task.FromResult((Response)new OkResponse());
    }
}
